import { Router } from 'hyper-express';
import requireUser from '../../middlewares/auth/requireUser';
import { qrcodeloginMessage } from './qrcodelogin';
import log from '../../helpers/logger';
import { webSocketStore } from '../websocket-store';

const authRouter = new Router();
// Create websocket route for handling protected upgrade

let remote_ws;
let remote_closed: boolean = false;

// HTTP 升级端点
authRouter.upgrade('/qrcodelogin/:channel', (req, res) => {
    try {
        // 准备升级上下文数据
        const connectionContext = {
          channel: req.params.channel,
          clientInfo: {
            ip: req.ip,
            ua: req.headers['user-agent']
          }
        };
    
        // 执行 WebSocket 协议升级
        // Reject upgrade request if valid key is not provided
        const client_id = req.query_parameters['client_id'];
        if (!client_id) return res.status(403).send();

        // Upgrade request normally
        res.upgrade({
          client_id,
          connectionContext
        });
      } catch (error) {
        console.error('协议升级失败:', error);
        res.status(500).json({ code: 'UPGRADE_FAILED' });
      }
});

// WebSocket 路由配置
authRouter.ws('/qrcodelogin/:channel', (ws) => {
    // Store websocket object for checking throught tests
    remote_ws = ws;
    const client_id = remote_ws.context.client_id
    log.info(client_id);
      // 注册客户端连接
    webSocketStore.addClient(client_id, ws);

    // Bind message handler
    ws.on('message', (message,client_id) => {
        // Echo messages until we receive 'CLOSE' message
        qrcodeloginMessage(message,client_id, ws);
    });

    // This will test that close event fires properly
    ws.on('close', () => {
      webSocketStore.removeClient(client_id);
      remote_closed = true;
      log.info('WebSocket closed');
    });
});

export default authRouter;
